package com.cgbl.cg.ui.work

import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.transition.Explode
import android.view.Window
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.adapter.ImgAdapter
import com.cgbl.cg.adapter.VideoAdapter
import com.cgbl.cg.adapter.WorkCommentAdapter
import com.cgbl.cg.databinding.AppActivityWorkDetailsBinding
import com.cgbl.cg.view.AddCollectPop
import com.cgbl.cg.view.WorkCollectPop
import com.cgbl.cg.view.WorkCommentChildPop
import com.cgbl.cg.view.WorkCommentPop
import com.cgbl.cg.vm.work.WorkDetailsViewModel
import com.lxj.xpopup.XPopup
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.model.CommentBean
import com.robot.base.model.WorksResourceBean
import com.shuyu.gsyvideoplayer.GSYVideoManager

/**
 * 作品详情
 */
@Route(path = AppConstants.Router.WORK.A_WORK_DETAIL)
class WorkDetailsActivity : GLBaseActivity<AppActivityWorkDetailsBinding, WorkDetailsViewModel>() {
    private lateinit var workCommentAdapter: WorkCommentAdapter
    private lateinit var imgAdapter: ImgAdapter
    private lateinit var videoAdapter: VideoAdapter
    private lateinit var workCollectPop: WorkCollectPop
    private lateinit var addCollectPop: AddCollectPop
    private var workCommentPop: WorkCommentPop? = null

    private var id = ""

    private var isPause = false

    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_work_details

    override fun initVariableId(): Int = BR.viewModel

    override fun onCreate(savedInstanceState: Bundle?) {

        // 设置一个exit transition
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.enterTransition = Explode()
            window.exitTransition = Explode()
        }
        super.onCreate(savedInstanceState)
    }

    override fun initComponents() {
        addSingleTitleBar("", R.mipmap.app_ic_work_share)
        initAdapter()
        initPop()
    }

    override fun initParam() {
        super.initParam()
        id = intent.getStringExtra("id") ?: ""
    }

    override fun initData() {
        super.initData()
        viewModel.id = id
        viewModel.getWorkDetail()
        viewModel.collectPage()
        viewModel.pageCommend(0, "", 0)
    }

    private fun initPop() {
        addCollectPop = AddCollectPop(this)
    }

    private fun initAdapter() {
        workCommentAdapter = WorkCommentAdapter()
        binding.mRvComment.apply {
            adapter = workCommentAdapter
        }

        imgAdapter = ImgAdapter()
        binding.mRvImg.apply {
            adapter = imgAdapter
        }

        videoAdapter = VideoAdapter()
        binding.mRvVideo.apply {
            adapter = videoAdapter
        }
        binding.mRvVideo.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, scrollState: Int) {}
            override fun onScrolled(
                recyclerView: RecyclerView,
                dx: Int,
                dy: Int
            ) {
                super.onScrolled(recyclerView, dx, dy)
                val firstVisibleItem =
                    (recyclerView.layoutManager!! as LinearLayoutManager).findFirstVisibleItemPosition()
                val lastVisibleItem =
                    (recyclerView.layoutManager!! as LinearLayoutManager).findLastVisibleItemPosition()
                //大于0说明有播放
                //大于0说明有播放
                if (GSYVideoManager.instance().playPosition >= 0) {
                    //当前播放的位置
                    val position = GSYVideoManager.instance().playPosition
                    //对应的播放列表TAG
                    if (GSYVideoManager.instance().playTag == videoAdapter::class.simpleName && (position < firstVisibleItem || position > lastVisibleItem)) {

                        //如果滑出去了上面和下面就是否，和今日头条一样
                        //是否全屏
                        if (!GSYVideoManager.isFullState(this@WorkDetailsActivity)) {
                            GSYVideoManager.releaseAllVideos()
                            videoAdapter.notifyItemChanged(position)
                        }
                    }
                }
            }
        })
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.uc.imgDataEvent.observe(this) {
            val list = it.map { it1 ->
                it1.filePath
            }
            imgAdapter.setNewInstance(list as MutableList<String>)
        }

        viewModel.uc.videoDataEvent.observe(this) {
            videoAdapter.setNewInstance(it as MutableList<WorksResourceBean>?)
        }

        viewModel.uc.refreshCommendChildDataEvent.observe(this) {
            val workCommentChildPop = WorkCommentChildPop(this, viewModel.commentBean, it)
            XPopup.Builder(this)
                .autoFocusEditText(false)
                .asCustom(workCommentChildPop)
                .show()

            workCommentChildPop.setConfirmClickListener { id, content, accountId ->
                workCommentChildPop.dismiss()
                viewModel.createWorkComment(content, id, accountId)
            }
        }

        viewModel.uc.showCommentEvent.observe(this) {
            workCommentPop = WorkCommentPop(this, workCommentAdapter.data)

            XPopup.Builder(this)
                .autoFocusEditText(false)
                .asCustom(workCommentPop)
                .show()

            workCommentPop?.setConfirmClickListener { id, content ->
//                workCommentPop.dismiss()
                viewModel.createWorkComment(content, "0")
            }

            workCommentPop?.setDetailClickListener {
                viewModel.commentBean = it
                viewModel.pageCommend(1, it.id ?: "", 1)
            }
        }

        viewModel.uc.refreshCommendDataEvent.observe(this) {
            workCommentAdapter.setNewInstance(it as MutableList<CommentBean>?)
            workCommentPop?.setData(it)
        }

        viewModel.uc.showCollectEvent.observe(this) {
            workCollectPop = WorkCollectPop(this, viewModel.list)
            XPopup.Builder(this)
                .asCustom(workCollectPop)
                .show()
            workCollectPop
                .setConfirmClickListener {
                    workCollectPop.dismiss()
                    viewModel.saveCollectWorks(it)
                }
                .setRightClickListener {
                    XPopup.Builder(this)
                        .moveUpToKeyboard(false)
                        .asCustom(addCollectPop)
                        .show()
                    addCollectPop.setCancelClickListener {
                        addCollectPop.dismiss()
                    }
                        .setConfirmClickListener { collectName, conllectInfo, status ->
                            viewModel.createCollect(collectName, conllectInfo, status)
                            workCollectPop.dismiss()
                            addCollectPop.dismiss()
                        }
                }
        }
    }

    override fun onBackPressed() {
        //为了支持重力旋转
        onBackPressAdapter()
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onResume()
        isPause = false
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        if (videoAdapter != null) {
            videoAdapter.onDestroy()
        }
    }

    /********************************为了支持重力旋转 */
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
//        if (videoAdapter != null && videoAdapter.getListNeedAutoLand() && !isPause) {
//            videoAdapter.onConfigurationChanged(this, newConfig)
//        }
    }

    private fun onBackPressAdapter() {
        //为了支持重力旋转
//        if (videoAdapter != null && videoAdapter.getListNeedAutoLand()) {
//            videoAdapter.onBackPressed()
//        }
    }
}